#!/bin/bash
#Author:ChenWk
#Desc:计算cpu使用率
#

#统计的核心
core=0;  #默认0为统计cpu平均使用率
case $1 in
  1 | 2 | 3 | 4 )
    core=$1 
    ;;
  * )
    core=0 ;;
esac

#延时x秒
interval=3
#CPU核心总数
cpu_num=`cat /proc/stat | grep cpu[0-9] -c`

start_idle=()
start_total=()
cpu_rate=()

    for((i=0;i<=${cpu_num};i++))
    {
        start=$(cat /proc/stat | grep "cpu" | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
        start_idle[$i]=$(echo ${start} | awk '{print $4}')
        start_total[$i]=$(echo ${start} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
    }
    sleep ${interval}
    for((i=0;i<=${cpu_num};i++))
    {
        end=$(cat /proc/stat | grep "cpu" | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
        end_idle=$(echo ${end} | awk '{print $4}')
        end_total=$(echo ${end} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
        idle=`expr ${end_idle} - ${start_idle[$i]}`
        total=`expr ${end_total} - ${start_total[$i]}`
        idle_normal=`expr ${idle} \* 100`
        cpu_usage=`expr ${idle_normal} / ${total}`
        cpu_rate[$i]=`expr 100 - ${cpu_usage}`
    }
        echo ${cpu_rate[$core]}